import java.io.*;
import java.util.*;

public class ReadProcesses {
	ArrayList<ProcessArrival> processArrivalSet = new ArrayList<ProcessArrival>();
	
	public ArrayList<ProcessArrival> read(String filename){
		return this.read(new String[]{"", filename});
	}
	
	public ArrayList<ProcessArrival> read(String[] args) {
		File file = null;
		Scanner input = null;
		
		//
		// Check to see if a file name was passed in
		// If no file name, exit
		// If there is a file name, try to open file and check if able to read file
		if (args.length > 1) {
			file = new File(args[1]);
			
			if(!file.exists()){
				System.out.println("This file \"" + args[1] + "\" does not exist.");
				System.exit(0);
			}
			else if(!file.isFile()){
				System.out.println("The given pathname is not a \"normal\" file. Exiting.");
				System.exit(0);
			}
		} 
		else {
			System.out.println("Need to pass in the filename for location of input. Exiting.");
			System.exit(0);
		}
		//
		// Open scanner to read in file
		try {
			input = new Scanner(file);
		} 
		catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		//
		// Designed for creating a process and updating the newly created
		// Process per line
		do
		{
			Process process = new Process();
			String fileline = input.nextLine(); // because file methods are
													// not as good as string
													// methods
			String[] tokens = fileline.split(" ");
			
			int arrivalTime = Integer.parseInt(tokens[0]);
			
			for (int i = 1; i < tokens.length; i++)
			{
				//
				// Read value of number of cycles
				int value = Integer.parseInt(tokens[i]);
				
				if (i % 2 == 1) // CPU cycles
				{
					for (int j = 0; j < value; j++) {
						process.addCycle(new CPUCycle());
					}
				}
				else if (i % 2 == 0) // IO Cycle
				{
					for (int j = 0; j < value; j++) {
						process.addCycle(new IOCycle());
					}
				}
			}
			
			processArrivalSet.add(new ProcessArrival(process, arrivalTime));
		} while (input.hasNextLine());// while
		
		input.close();
		
		return processArrivalSet;
	} // main
}// class
